package org.charles.zhifou.common.enums;

import jakarta.annotation.Nonnull;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * <h1>parmas 参数中的枚举类转换</h1>
 *
 * @author charles
 * @version 1.0
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    // 该方法返回一个 Converter 实现类对象 (工厂模式)
    @Override
    @Nonnull
    public <T extends BaseEnum> Converter<String, T> getConverter(@Nonnull Class<T> targetType) {
        return code -> {
            // 因为此处 T 为泛型, 因此只能基于 Class 对象的 .getEnumConstants() 方法获取所有枚举类对象
            T[] enumConstants = targetType.getEnumConstants();
            for (T enumConstant : enumConstants) {
                if (enumConstant.getCode().equals(Integer.valueOf(code))) {
                    return enumConstant;
                }
            }

            throw new IllegalArgumentException("Unknown code for \"" + targetType.getName() + "\": " + code);
        };
    }
}
